[toc]
python基础二十七 python操作mysql
1.安装pymysql
pip3 install pymysql
2.python连接mysql
2.1 python连接mysql语法
//导入pymysql模块
import pymysql
//打开数据库连接
⚠️⚠️⚠️指定字符集的时候utf-8在这里的写法为utf8
conn = pymysql.connect("数据库ip","用户","密码","数据库","端口(不写默认为3306)","字符集")
//使用cursor()方法获取操作游标
cursor = conn.cursor()
//使用execute()方法执行SQL操作
cursor.execute("SQL语句")
//使用fetchone()方法获取单条数据
data = cursor.fetchone()
print ("Database version : %s " %data)
//关闭游标
cursor.close()
//关闭数据库连接
conn.close()
2.2 python连接mysql简单查询示例
//数据库db1中有一张t1表,表内容如下
mysql> select * from t1;
+------+--------+
| id | name |
+------+--------+
| 1 | 小明 |
| 2 | 小颖 |
| 3 | 小丽 |
+------+--------+
3 rows in set (0.00 sec)
//接下来连接数据库进行操作
#导入pymysql模块
import pymysql
#打开数据库连接
conn = pymysql.connect(
host='xxx', user='xxx', password="xxx",
database='db1', port=3306, charset='utf8',
)
#创建游标
cursor = conn.cursor()
#定义一个变量,存放sql语句
sql = 'select * from t1'
#使用execute()方法执行sql操作
cursor.execute(sql)
#使用fetchall()方法获取所有数据
data = cursor.fetchall()
#打印查询的内容
print(data)
((1, '小明'), (2, '小颖'), (3, '小丽'))
#关闭游标
cursor.close()
#关闭连接
conn.close()
3.python操作mysql
3.1 创建表操作
#导入pymysql模块
import pymysql
#打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
#使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
#使用execute()方法执行 SQL,如果表存在则删除
cursor.execute("drop table if exists t2")
#使用预处理语句创建表
sql = """create table t2(
id int not null,
age int not null,
name char(10) not null,
hobby set('唱','跳','rap','篮球'))"""
#执行sql语句
cursor.execute(sql)
#查看结果
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| t1 |
| t2 |
+---------------+
2 rows in set (0.00 sec)
mysql> desc t2;
+-------+---------------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------------------------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| age | int(11) | NO | | NULL | |
| name | char(10) | NO | | NULL | |
| hobby | set('唱','跳','rap','篮球') | YES | | NULL | |
+-------+---------------------------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
#关闭游标
cursor.clos()
#关闭数据库连接
conn.close()